<template>
  <div>
    <headerXX :name="title"></headerXX>
    <van-pull-refresh
      class="pull-refresh"
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <van-empty
        v-if="goodList.length == 0 && !error"
        image="search"
        description="未找到数据"
      />
      <van-empty v-if="error" image="error" description="网络错误" />
      <van-list
        :immediate-check="false"
        v-model:loading="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="queryList"
      >
        <div class="ulbox">
          <div class="ul" v-for="(item, index) in goodList" :key="index">
            <div class="li">
              <div style="display: flex; align-items: center">
                <div class="li_left">
                  <img :src="item.goodImage" mode="" />
                </div>
                <div class="li_right">
                  <div style="font-weight: 600; font-size: 18px">
                    {{ item.goodName }}
                  </div>
                  <div class="description_wc">
                    {{ item.goodDescription }}
                  </div>
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    "
                  >
                    <div class="price" style="font-size: 24rpx; color: #35c2a8">
                      ￥{{ item.goodPrice }}元/{{ item.productSpecification }}
                    </div>
                    <div v-if="item.productRemain > 0" style="color: #82848a">
                      剩余{{ item.productRemain
                      }}{{ item.productSpecification }}
                    </div>
                    <div v-else>暂无库存</div>
                  </div>
                  <div class="li_right__num">
                    <van-stepper
                      class="stepper"
                      v-model="item.goodQty"
                      theme="round"
                      min="0"
                      :max="item.productRemain"
                      :default-value="0"
                      @change="valChange"
                      input-width="24px"
                      button-size="18px"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <template #error>
          <div class="error-tip" @click="retryLoad">
            <van-icon name="warning" />
            <span>加载失败，点击重试</span>
          </div>
        </template>
      </van-list>
    </van-pull-refresh>
    <div class="DI" style="position: fixed; bottom: 0">
      <div style="font-size: 16px; margin-top: 10px">
        合计费用：{{ ZJG }} <text v-if="ZJG > 0">元</text>
      </div>
      <van-button
        style="width: 300px; margin-bottom: 20px"
        class="buy"
        color="#36C2A8"
        @click="jumpToBuy()"
        >预 订</van-button
      >
    </div>
  </div>
</template>

<script>
import { testUserMessage } from "../../common/testUser.js";
import headerXX from "../../components/title.vue";
import { getCultureProductList } from "@/api/realAssets/icsharedstation/WCCP/index.js";
export default {
  components: { headerXX },
  data() {
    return {
      title: "文创产品",
      siteData: JSON.parse(localStorage.getItem("siteData")),
      loading: false,
      finished: false,
      refreshing: false,
      ZJG: 0.0,
      goodList: [],
      error: false,
      pageData: {
        pageNumber: 1,
        pageSize: 10,
      },
    };
  },
  created() {},
  methods: {
    queryList() {
      this.loading = true;
      // if (route.query.XX) {
      //   siteData.value.id = JSON.parse(decodeURIComponent(route.query.XX).replace(/%25/g, "%")).siteId
      // }
      if (this.error) return; // 如果当前是错误状态，不自动触发加载
      if (this.refreshing) {
        this.goodList = [];
      }
      console.log("111", {
        siteId: this.siteData.id,
        pageNumber: this.pageData.pageNumber,
        pageSize: this.pageData.pageSize,
      });
      getCultureProductList({
        siteId: this.siteData.id,
        pageNumber: this.pageData.pageNumber,
        pageSize: this.pageData.pageSize,
      })
        .then((res) => {
          if (res.resultMessage != "SUCCESS") {
            this.goodList = [];
            this.error = true; // 显示错误提示
          } else if (res.data.length == 0) {
            this.goodList = [];
            this.finished = true;
          } else {
            let dataList = res.data.map((item) => {
              return {
                goodId: item.id,
                goodName: item.productName,
                goodImage: item.productImage,
                goodPrice: item.productPrice,
                goodQty: 0,
                goodSiteId: item.siteId,
                goodSpecification: item.productSpecification,
                goodDescription: item.productDescription,
                remark: item.remark,
                productRemain: item.productRemain,
                productSpecification: item.productSpecification,
                productSum: item.productSum,
              };
            });
            console.log(dataList);
            this.goodList = [...this.goodList, ...dataList];
          }
          this.loading = false;
          // 判断是否已加载完所有数据
          if (this.goodList.length == res.pageNum) {
            this.finished = true;
          } else {
            this.pageData.pageNumber++;
          }
          this.refreshing = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    jumpToBuy(item) {
      if (this.ZJG == 0) {
        Dialog.alert({
          message: "请选择一项商品",
        });
        return;
      }
      Dialog.confirm({
        // title: '预定提示',
        message:
          "是否确认预订本产品，预订成功后请移步至共享驿站服务台购买(支持刷卡/微信/支付宝付款)",
      })
        .then(() => {
          let SPlist = [];
          let itemList = [];
          this.goodList.forEach((item) => {
            if (item.goodQty > 0) {
              SPlist.push({
                id: item.goodId,
                requestQty: item.goodQty,
              });
              itemList.push(item);
              console.log(item);
            }
          });
          const currentTimeStamp = moment().unix();
          const min = BigInt("1" + "0".repeat(18));
          const max = BigInt("1" + "0".repeat(19));
          const randomNum =
            min + BigInt(Math.floor(Math.random() * Number(max - min)));

          let itemXX = {
            SBBT: "文创产品",
            orderNumber: currentTimeStamp + randomNum.toString(), //预约编号
            siteId: this.siteData.id, //服务点id
            orderProject: "文创产品", //预约项目
            orderProjectType: "0", //0:   1:  (区分健康自测类型与其他类型)
            orderCreationTime: moment().format("YYYY-MM-DD"), //下单时间
            goodInfo: SPlist,
            estimateArrivalTime: "", //服务时间
            estimateArrivalTimeTitle: "",
            estimateSumPrice: 0, //预估费用
            orderSubType: "", //预约类型
            serviceDescription: "", //服务介绍
            orderLocation: "", //预约地址(非空展示)
            serviceTip: "", //温馨提示(非空展示)
            goodSumPrice: "", //总价
            serviceTitleList: ["商品名称", "单价", "数量", "小计"], //服务标题
            goodList: [...itemList], //商品列表
          };
          // console.log(SPlist)
          // console.log(itemXX, "1111")
          // getAccessToken(itemXX, "文创产品")
        })
        .catch(() => {
          // on cancel
        });
    },
    valChange(e) {
      this.ZJG = 0;
      this.goodList.forEach((item) => {
        if (item.goodId == e.name) {
          item.goodQty = e.value;
        }
        this.ZJG += item.goodQty * item.goodPrice;
      });
    },
    onRefresh() {
      this.pageData.pageNumber = 1;
      this.pageData.pageSize = 10;
      this.finished = false;
      this.error = false;
      this.loading = true;
      this.refreshing = true;
      this.queryList();
    },
    retryLoad() {
      this.error = false;
      this.loading = true;
      this.queryList();
    },
  },
  mounted() {
    testUserMessage("文创产品").then((siteData) => {
      this.siteData = siteData[0];
      this.queryList();
    })
  },
};
</script>
<style>
.van-sidebar-item--select:before {
  background-color: rgb(2, 117, 113) !important;
}
.van-stepper__plus {
  background-color: #36c2a8 !important;
}
.van-stepper__minus {
  color: #36c2a8 !important ;
  border: 0.02667rem solid #36c2a8 !important;
}
</style>
<style lang="less" scoped>
@import "../../static/css/index.less";
@import "../../static/css/GYcSS.less";
img {
  width: 100px;
  height: 90px;
  border-radius: 5px;
}
.pull-refresh {
  height: calc(
    var(--real-vh, 1vh) * 100 - 150px - env(safe-area-inset-bottom) -
      env(safe-area-inset-top)
  );
}
.description_wc {
  margin: 5px 0 10px 0;
  display: -webkit-box;
  font-size: 10px;
  line-height: 10px;
  height: 38px;
  width: 70%;
  margin: 5px 0;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #82848a;
}
.stepper {
  --van-stepper-background-color: #36c2a8;
  --van-stepper-button-icon-color: #36c2a8;
  --van-stepper-button-disabled-color: #36c2a8;
  --van-stepper-button-disabled-icon-color: #36c2a8;
  --van-stepper-button-round-theme-color: #36c2a8;
  --van-stepper-input-disabled-text-color: #36c2a8;
  --van-stepper-input-disabled-background-color: #36c2a8;
}
</style>
